package com.common.wx;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class WebUtil {
	/**
	 * 发起http get请求
	 */
	public static JSONObject doGet(String requestUrl) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String responseContent = null;
		JSONObject result = null;

		try {
			HttpGet httpGet = new HttpGet(requestUrl);
			response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
			result = JSON.parseObject(responseContent);
		} catch (IOException e) {
			System.out.println("HTTP请求异常：" + e.getMessage());
		}
		System.out.println("responseData:" + result);
		return result;
	}

	/**
	 * @Title 创建微信发送请求post实体 charset消息编码 ，contentType消息体内容类型，
	 *        url微信消息发送请求地址，data为post数据，token鉴权token
	 * @return String
	 */
	public static String post(String charset, String CONTENT_TYPE, String contentType, String url, String data)
			throws IOException {

		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader(CONTENT_TYPE, contentType);
		httpPost.setEntity(new StringEntity(data, charset));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		String resp;
		try {
			HttpEntity entity = response.getEntity();
			resp = EntityUtils.toString(entity, charset);
			EntityUtils.consume(entity);
		} finally {
			response.close();
		}
		return resp;
	}
}
